/*
 * @Author: lxc
 * @Date: 2020-10-10 14:56:58
 * @LastEditTime: 2020-12-23 20:26:07
 * @LastEditors: lxc
 * @Description: In User Settings Edit
 * @FilePath: \vue3.0-demo\src\utils\axios.ts
 */
import axios from 'axios';
import store from '../store/index';
import { message } from 'ant-design-vue';
import { logins } from '../api/index';

const instance = axios.create({
    baseURL: process.env.VUE_APP_URL,
    timeout: 3000
})


instance.interceptors.request.use((config: any) => {
    var token: String | null = store.getters.token;
    if (token) {
        // 后台接口定义传入的token
        config.headers['Authorization'] = token;
    }

    return config
})

instance.interceptors.response.use((res: any) => {
    return res.data
}, async err => {
    console.log(err.config);
    
    switch (err.response.status) {
        case 401:
            var email = localStorage.getItem('email')
            var password = localStorage.getItem('password')
            let res: any = await logins({ email, password })
            localStorage.setItem('token', res.token)
            err.response.config.headers['Authorization'].replace('Bearer ', res.token);
            break;
        case 404:
            message.error('网络请求不存在');
            break;
        case 400:
            message.error(err.response.data.msg);
            break;
        case 500:
            message.error('服务器错误');
            break;

    }
    return Promise.reject(err)
})

export function request(opts: any) {
    return instance(opts);
}
